package com.gexiaobao.pigeon.ui.dialog;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.drawable.Drawable;
import android.os.CountDownTimer;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.core.content.ContextCompat;

import com.gexiaobao.pigeon.R;
import com.gexiaobao.pigeon.app.util.RxToast;

import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.regex.PatternSyntaxException;

/**
 * Created by babosa
 * 自定义支付密码组件
 */

public class PayPassView extends RelativeLayout {
    private Activity mContext;//上下文
    private GridView mGridView; //支付键盘
    public String strPass = "";//保存密码
    public VertifyCodeTextView[] mTvPass;//密码数字控件
    private ImageView mImageViewClose;//关闭
    private TextView mTvForget;//忘记密码
    private TextView mTvSubmit;//确定提交
    private TextView mTvHint;//提示 (提示:密码错误,重新输入)
    private List<Integer> listNumber;//1,2,3---0
    private View mPassLayout;//布局

    /**
     * 按钮对外接口
     */
    public static interface OnPayClickListener {
        void onPassFinish(String passContent);

        void onPayClose();

        void onPayForget();

        void onPaySubmit();
    }

    private OnPayClickListener mPayClickListener;

    public void setPayClickListener(OnPayClickListener listener) {
        mPayClickListener = listener;
    }

    //在代码new使用
    public PayPassView(Context context) {
        super(context);
    }

    //在布局文件中使用的时候调用,多个样式文件
    public PayPassView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    //在布局文件中使用的时候调用
    public PayPassView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        this.mContext = (Activity) context;

        initView();//初始化
        this.addView(mPassLayout); //将子布局添加到父容器,才显示控件
    }

    /**
     * 初始化
     */
    private void initView() {
        mPassLayout = LayoutInflater.from(mContext).inflate(R.layout.div_view_paypass_layout, null);
        mImageViewClose = (ImageView) mPassLayout.findViewById(R.id.iv_close);//关闭
        mTvForget = (TextView) mPassLayout.findViewById(R.id.tv_forget);//忘记密码
        mTvSubmit = (TextView) mPassLayout.findViewById(R.id.tv_submit);//确定提交
        mTvHint = (TextView) mPassLayout.findViewById(R.id.tv_passText);//提示文字
        mTvPass = new VertifyCodeTextView[6];                                  //密码控件
        mTvPass[0] = (VertifyCodeTextView) mPassLayout.findViewById(R.id.tv_pass1);
        mTvPass[1] = (VertifyCodeTextView) mPassLayout.findViewById(R.id.tv_pass2);
        mTvPass[2] = (VertifyCodeTextView) mPassLayout.findViewById(R.id.tv_pass3);
        mTvPass[3] = (VertifyCodeTextView) mPassLayout.findViewById(R.id.tv_pass4);
        mTvPass[4] = (VertifyCodeTextView) mPassLayout.findViewById(R.id.tv_pass5);
        mTvPass[5] = (VertifyCodeTextView) mPassLayout.findViewById(R.id.tv_pass6);
        mGridView = (GridView) mPassLayout.findViewById(R.id.gv_pass);

        timeCount.start();

        mImageViewClose.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                cleanAllTv();
                mPayClickListener.onPayClose();
            }
        });
        mTvForget.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                timeCount.start();
                mPayClickListener.onPayForget();
            }
        });


        mTvSubmit.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                if (strPass.length() == 6) {
                    mPayClickListener.onPassFinish(strPass);//请求服务器验证密码
                } else {
                    RxToast.showToast("验证码不足6位");
                }
            }
        });


        //初始化数据
        listNumber = new ArrayList<>();
        for (int i = 1; i < 10; i++) {
            listNumber.add(i);
        }
        listNumber.add(10);
        listNumber.add(0);
        listNumber.add(R.mipmap.ic_pay_del0);

        mGridView.setAdapter(adapter);
    }


    /**
     * GridView的适配器
     */

    BaseAdapter adapter = new BaseAdapter() {
        @Override
        public int getCount() {
            return listNumber.size();
        }

        @Override
        public Object getItem(int position) {
            return listNumber.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @SuppressLint({"ClickableViewAccessibility", "SetTextI18n"})
        @Override
        public View getView(final int position, View convertView, ViewGroup parent) {
            final ViewHolder holder;
            if (convertView == null) {
                convertView = View.inflate(mContext, R.layout.div_view_paypass_gridview_item, null);
                holder = new ViewHolder();
                holder.btnNumber = (TextView) convertView.findViewById(R.id.btNumber);
                convertView.setTag(holder);
            } else {
                holder = (ViewHolder) convertView.getTag();
            }
            //-------------设置数据----------------
            holder.btnNumber.setText(listNumber.get(position) + "");
            if (position == 9) {
                holder.btnNumber.setText("");
                holder.btnNumber.setBackgroundColor(mContext.getResources().getColor(R.color.graye3));
            }
            if (position == 11) {
                holder.btnNumber.setText("");
                holder.btnNumber.setBackgroundResource(listNumber.get(position));
            }
            //监听事件----------------------------
            if (position == 11) {
                holder.btnNumber.setOnTouchListener((v, event) -> {
                    switch (event.getAction()) {
                        case MotionEvent.ACTION_DOWN:
                        case MotionEvent.ACTION_MOVE:
                            holder.btnNumber.setBackgroundResource(R.mipmap.ic_pay_del1);
                            break;
                        case MotionEvent.ACTION_UP:
                            holder.btnNumber.setBackgroundResource(R.mipmap.ic_pay_del0);
                            break;
                    }
                    return false;
                });
            }
            holder.btnNumber.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (position < 11 && position != 9) {//0-9按钮
                        if (strPass.length() == 6) {
                            return;
                        } else {
                            Integer nowNum = listNumber.get(position);
                            strPass = strPass + nowNum;//得到当前数字并累加
                            mTvPass[strPass.length() - 1].setText("" + nowNum); //设置界面*
                            //输入完成
//                            if(strPass.length()==6){
//                                mPayClickListener.onPassFinish(strPass);//请求服务器验证密码
//                            }
                        }
                    } else if (position == 11) {//删除
                        if (strPass.length() > 0) {
                            mTvPass[strPass.length() - 1].setText("");//去掉界面*
                            strPass = strPass.substring(0, strPass.length() - 1);//删除一位
                        }
                    }
                    if (position == 9) {//空按钮
                    }
                }
            });

            return convertView;
        }
    };

    static class ViewHolder {
        public TextView btnNumber;
    }


    /**
     * 关闭图片
     * 资源方式
     */
    public void setCloseImgView(int resId) {
        mImageViewClose.setImageResource(resId);
    }

    /**
     * 关闭图片
     * Bitmap方式
     */
    public void setCloseImgView(Bitmap bitmap) {
        mImageViewClose.setImageBitmap(bitmap);
    }

    /**
     * 关闭图片
     * drawable方式
     */
    public void setCloseImgView(Drawable drawable) {
        mImageViewClose.setImageDrawable(drawable);
    }


    /**
     * 设置忘记密码文字
     */
    public void setForgetText(String text) {
        mTvForget.setText(text);
    }

    /**
     * 设置忘记密码文字大小
     */
    public void setForgetSize(float textSize) {
        mTvForget.setTextSize(textSize);
    }

    /**
     * 设置忘记密码文字颜色
     */
    public void setForgetColor(int textColor) {
        mTvForget.setTextColor(textColor);
    }

    /**
     * 设置提醒的文字
     */
    public void setHintText(String text) {
        mTvHint.setText(text);
    }

    /**
     * 设置提醒的文字大小
     */
    public void setTvHintSize(float textSize) {
        mTvHint.setTextSize(textSize);
    }

    /**
     * 设置提醒的文字颜色
     */
    public void setTvHintColor(int textColor) {
        mTvHint.setTextColor(textColor);
    }

    /**
     * 清楚所有密码TextView
     */
    public void cleanAllTv() {
        strPass = "";
        for (int i = 0; i < 6; i++) {
            mTvPass[i].setText("");
        }
    }


    TimeCount timeCount = new TimeCount(60000, 1000);

    public Boolean isChinaPhoneLegal(String str) {
        try {
            String regExp = "^((13[0-9])|(15[^4])|(18[0-9])|(17[0-8])|(147,145))\\d{8}$";
            Pattern p = Pattern.compile(regExp);
            Matcher m = p.matcher(str);
            return m.matches();
        } catch (PatternSyntaxException e) {
            return false;
        }
    }

    class TimeCount extends CountDownTimer {
        public TimeCount(long millisInFuture, long countDownInterval) {
            super(millisInFuture, countDownInterval);
        }

        @SuppressLint("SetTextI18n")
        @Override
        public void onTick(long millisUntilFinished) {
            mTvForget.setBackground(ContextCompat.getDrawable(mContext, R.drawable.round_btn_checking_b_g));
            mTvForget.setTextColor(ContextCompat.getColor(mContext, R.color.black));
            mTvForget.setClickable(false);
            mTvForget.setText("(" + millisUntilFinished / 1000 + ") 秒后可重发");
        }

        @Override
        public void onFinish() {
            mTvForget.setText(mContext.getString(R.string.Get_the_verification_code_again));
            mTvForget.setClickable(true);
            mTvForget.setBackground(ContextCompat.getDrawable(mContext, R.color.white));
            mTvForget.setTextColor(ContextCompat.getColor(mContext, R.color.bg_light_bllue));
        }

    }
}
